const http = require('http');
const url = require('url');
const util = require('util');
const queryString = require('querystring');

function onRequest(request,response){
    response.writeHead(200,{"Content-Type": "text/plain"});

    // 解析url参数
    let params = url.parse(request.url, true).query;
    response.write("website: "+params.name);
    response.write("\n");
    response.write("url: "+params.url);
    response.write("\n");
    response.write("Hello httpServer!");
    response.end();
}

// post 请求
var postHTML = 
  '<html><head><meta charset="utf-8"><title>菜鸟教程 Node.js 实例</title></head>' +
  '<body>' +
  '<form method="post">' +
  '网站名： <input name="name"><br>' +
  '网站 URL： <input name="url"><br>' +
  '<input type="submit">' +
  '</form>' +
  '</body></html>';

function onPostReq(req, res){
    var body = "";
    req.on('data', function(chunk){
        body += chunk;
    });

    req.on('end', function(){
        body = queryString.parse(body);
        res.writeHead(200, {'Content-Type': 'text/html;charset=uft8'});
        if(body.name && body.url){
            res.write('website:'+body.name);
            res.write('<br>');
            res.write('URL: '+body.url);
        }else{
            res.write(postHTML);
        }
        res.end;
    });
}

http.createServer(onPostReq).listen(8888);